﻿using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using web.Models;

namespace web
{
    public class MyLib
    {
        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void MyLibInit();

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void MyLibFinit();

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int MyAdd(int a, int b);

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern bool MyGetMessage([MarshalAs(UnmanagedType.LPStr)] StringBuilder msg, ref UInt32 size);

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        [return: MarshalAs(UnmanagedType.BStr)]
        public static extern string MyGetBStr();

        // unsafe
        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UI1)]
        private static extern byte[] MyGetCStr();

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        [return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UI1)]
        private static extern byte[] MyGetWStr();

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        public static extern bool MySetMessage(string msg);

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool MyGetResult([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_I4)] ref int[]? ar);

        [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool MyGetImage([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UI1)] ref byte[]? ar);

        public static string? GetCStr()
        {
            byte[]? stringPointer = MyGetCStr();
            if (stringPointer != null)
            {
                return Console.OutputEncoding.GetString(stringPointer);
            }
            else
            {
                return null;
            }
        }

        public static string? GetWStr()
        {
            byte[]? stringPointer = MyGetWStr();
            if (stringPointer != null)
            {
                return Encoding.Unicode.GetString(stringPointer);
            }
            else
            {
                return null;
            }
        }
    }
}
